

import { actionsTypes } from '../../store'

export function getInitState() {
  return {
    isShow: false,
    editInfo: null,
    form: {
      task_name: '',
      task_desc: ''
    },
    scheduleForm: {
      schedule_name: '',
      schedule_desc: '',
      date: [],
      cron: '',
    },
    notebookInfo: null,
    engineId: null,
    callback: () => { }
  }
}

export default {
  namespaced: true,
  state: getInitState(),
  mutations: {
    [actionsTypes.SET_MODAL]: (state, payload = {}) => {
      for (const [key, value] of Object.entries(payload)) {
        state[key] = value
      }
    },
    // [actionsTypes.SET_MODAL_FORM]: (state, payload = {}) => {
    //   for (const key of Object.keys(state.form)) {
    //     state.form[key] = payload[key] !== undefined ? payload[key] : state.form[key]
    //   }
    // },
    [actionsTypes.SET_MODAL_FORM]: (state, payload = {}) => {
      for (const key of Object.keys(state.scheduleForm)) {
        state.scheduleForm[key] = payload[key] !== undefined ? payload[key] : state.scheduleForm[key]
      }
    },
    [actionsTypes.SHOW_MODAL]: state => {
      state.isShow = true
    },
    [actionsTypes.HIDE_MODAL]: state => {
      state.isShow = false
    },
    [actionsTypes.RESET_MODAL]: state => {
      for (const [key, value] of Object.entries(getInitState())) {
        state[key] = value
      }
    },
    // [actionsTypes.RESET_MODAL_FORM]: state => {
    //   for (const [key, value] of Object.entries(getInitState().form)) {
    //     state.form[key] = value
    //   }
    // },
    [actionsTypes.RESET_MODAL_FORM]: state => {
      for (const [key, value] of Object.entries(getInitState().scheduleForm)) {
        state.scheduleForm[key] = value
      }
    },
    [actionsTypes.SET_EDIT_INFO]: (state, payload = {}) => {
      state.editInfo = payload
    },
  },
  actions: {
    [actionsTypes.CALL_MODAL]({ commit }, payload) {
      let scheduleInfo = {}
      if (payload.data.scheduleInfo) {
        const { name: schedule_name, schedule: { startTime: start_time, endTime: end_time, crontab: cron }, description: schedule_desc } = payload.data.scheduleInfo
        scheduleInfo = { schedule_name, date: [start_time, end_time], cron, schedule_desc }
      }
      return new Promise(resolve => {
        commit(actionsTypes.SET_MODAL, { callback: resolve, notebookInfo: payload.data.currentNotebook, engineId: payload.data.engineId })
        // 初始化 form 中的数据
        commit(actionsTypes.SET_MODAL_FORM, scheduleInfo)
        commit(actionsTypes.SET_EDIT_INFO, payload.editInfo)
        commit(actionsTypes.SHOW_MODAL)
      })

      // return new Promise(resolve => {
      //   commit(actionsTypes.SET_MODAL, { callback: resolve, notebookInfo: payload })
      //   // 初始化 form 中的数据
      //   commit(actionsTypes.SET_MODAL_FORM, { task_name: payload.name })
      //   commit(actionsTypes.SHOW_MODAL)
      // })
    }
  }
}
